package org.lq.util;

import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.apache.log4j.Logger;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author 无语
 * @create 2020-10-02 17:09
 */
public class JDBCUtil {


    private static final Logger log = Logger.getLogger(JDBCUtil.class);
    private static Properties properties = new Properties();
    private static DataSource dataSource;
    static {
        InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("dbcp.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            log.error("配置文件读取失败",e);
        }
        log.info("数据库工具类，加载完配置文件！");
    }


    public static DataSource getDataSource() {
        log.info("--->获取数据源对象"+dataSource.toString());
        return dataSource;
    }

    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}
